package com.wink_172.library.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.http.SslError;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.ViewGroup;
import android.webkit.CookieManager;
import android.webkit.CookieSyncManager;
import android.webkit.SslErrorHandler;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.LinearLayout;

import androidx.databinding.DataBindingUtil;


import com.wink_172.library.R;
import com.wink_172.library.databinding.ActivityWebBinding;
import com.wink_172.library.model.Constants;
import com.wink_172.library.utils.FileUtil;
import com.wink_172.library.view.ActionBarView;

import java.io.File;


public class WebActivity extends SmartActivity {

    private WebView mWeb;
    public ActivityWebBinding binding;

    public static void startActivity(Context context, Object... args) {
        Intent intent = new Intent(context, WebActivity.class);

        intent.putExtra(Constants.PARAM_DATA1, (String) args[0]);
        intent.putExtra(Constants.PARAM_DATA2, (String) args[1]);
        context.startActivity(intent);
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStatusBarLightMode();

        binding = DataBindingUtil.setContentView(this, R.layout.activity_web);
        binding.setOnClickListener(this);

        initView();
        initWebView();
        init();
    }

    private void initView() {

    }


    private void init() {

        String title = getIntent().getStringExtra(Constants.PARAM_DATA1);
        ((ActionBarView) binding.actionBar).updateAllContent(R.mipmap.icon_nav_arrow, title,"");
        ((ActionBarView) binding.actionBar).setCallback(new ActionBarView.ICallback() {
            @Override
            public void onSendEvent(int event, String content) {
                if (event == ActionBarView.LEFT_BTN) {
                    finish();

                }

            }
        });

        String url = getIntent().getStringExtra(Constants.PARAM_DATA2);
        loadUrl(url);
    }

    private void initWebView() {
        mWeb = new WebView(this);
        LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.MATCH_PARENT);
        mWeb.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        mWeb.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
        mWeb.setBackgroundColor(getResources().getColor(android.R.color.white));
        mWeb.setLayoutParams(param);
        binding.web.addView(mWeb);
        initWebViewSettings(mWeb);
        setWebClientConfig(mWeb);
//        addJsNativeInterface(mWeb);

    }


    private void initWebViewSettings(WebView web) {
        CookieSyncManager.createInstance(this);
        CookieManager cm = CookieManager.getInstance();
        cm.setAcceptCookie(true);
        WebSettings settings = web.getSettings();
        settings.setSupportZoom(true);
        settings.setBuiltInZoomControls(false);

        settings.setJavaScriptEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setDatabaseEnabled(true);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setCacheMode(WebSettings.LOAD_DEFAULT);
        File cache = FileUtil.getAppFilesDir("cache");
        String cachePath = cache != null && cache.exists() ? cache.getPath() : getCacheDir().getPath();
        settings.setDatabasePath(cachePath);
        settings.setAppCachePath(cachePath);
        settings.setAppCacheEnabled(true);

    }

    private void setWebClientConfig(WebView view) {
        view.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                if (!TextUtils.isEmpty(url) && url.startsWith(WebView.SCHEME_TEL)) {
                    return true;
                }
                view.loadUrl(url);
                return true;
            }

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {

            }

            @Override
            public void onPageFinished(WebView view, String url) {


            }

            @Override
            public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
                handler.proceed();
            }

        });

        view.setWebChromeClient(new WebChromeClient() {
            public void onReceivedTitle(WebView view, String title) {
                if (view.canGoBack()) {

                }

            }

            @Override
            public void onProgressChanged(WebView view, int newProgress) {

            }

        });

        try {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
                view.removeJavascriptInterface("searchBoxJavaBridge_");
                view.removeJavascriptInterface("accessibility");
                view.removeJavascriptInterface("accessibilityTraversal");
            }
        } catch (Exception e) {

        }
    }

    private static final String TAG = "WebActivity";

    private void loadUrl(String href) {
        if (!TextUtils.isEmpty(href)) {
            try {
                Log.e(TAG, "web 加载的链接 " + href);
                mWeb.loadUrl(href);
            } catch (Exception e) {

            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (binding.web != null) {
            binding.web.removeView(mWeb);
        }

        mWeb.stopLoading();
        mWeb.clearHistory();
        mWeb.clearFormData();
        mWeb.clearView();

        mWeb.removeAllViews();

        try {
            mWeb.destroy();
        } catch (Exception e) {

        }


    }

    @Override
    public void finish() {
        ViewGroup view = (ViewGroup) getWindow().getDecorView();
        view.removeAllViews();
        super.finish();
    }

}
